Ext.Loader.setConfig({enabled: true});
//Ext.Loader.setPath({'Ext.ux' : 'extjs4/ux','Ext.ux.exporter':'extjs4/ux/exporter'});
Ext.Loader.setPath({'Ext.ux' : 'extjs4/ux'});
Ext.require([
             'Ext.grid.*',
             'Ext.data.*',
             'Ext.ux.grid.FiltersFeature',
             'Ext.toolbar.Paging',
             'Ext.ux.ajax.JsonSimlet',
             'Ext.ux.ajax.SimManager',
             'Ext.ux.grid.Printer'        
]);
Ext.define('TS.controller.RpARecBills',{
	extend: 'Ext.app.Controller',
	
	models:['rp.ArpBillModel'],
	stores:['rp.ARecBillStore'],
	views:['rp.RpARecBillList'],
	init:function() {
		this.control({
			'rparecbilllist button[action=search]':{click:this.search},
			'rparecbilllist button[action=advsearch]':{click:this.advsearch},
			'rparecbilllist triggerfield[name=customer]':{specialkey:this.searchCustomer,change:this.clearCustId},
			'rparecbilllist button[action=createBill]':{click:this.createBill},
			'rparecbilllist button[action=editBill]':{click:this.editBill},
			'rparecbilllist button[action=deleteBill]':{click:this.deleteBill},
			'rparecbilllist button[action=archiveBill]':{click:this.archiveBill},
			'rparecbilllist button[action=unArchiveBill]':{click:this.unArchiveBill},
			'rparecbilllist button[action=printBill]':{click:this.printBill},
			'rparecbilllist button[action=exportBill]':{click:this.exportBill},
			'rparecbilllist grid':{itemdblclick:this.dbclickBill}
		});
	},
	
	//查询应收单记录
	search:function(button) {
		if(button == null) {
			button = Ext.ComponentQuery.query('rparecbilllist button[action=search]')[0];
		}
		var begDateField = button.up('panel').down('datefield[name=begDate]');
		var endDateField = button.up('panel').down('datefield[name=endDate]');
		var custId = button.up('panel').down('hiddenfield[name=custId]');
		var grid = button.up('panel[alias=widget.rparecbilllist]').down('gridpanel');
		grid.store.on("beforeload",function(){
	        Ext.apply(grid.store.proxy.extraParams, {begDate:begDateField.getRawValue(),endDate:endDateField.getRawValue(),custId:custId.value});
	    });
		grid.store.loadPage(1,{
			params:{begDate:begDateField.getRawValue(),endDate:endDateField.getRawValue(),custId:custId.value},
			callback:function(records){
			},
			scope:this			
		});
	},
	//高级查询
	advsearch:function(){
		Ext.MessageBox.alert('ThinkGsp','该功能未实现。');
	},
	//检索客户
	searchCustomer:function(field,e) {
		var custIdField = field.up('panel').down('hiddenfield[name=custId]');
		if(e.getKey() == e.ENTER && field.value != '') {
		    	var view=Ext.create('TS.view.base.CustomerSearchDialog');
		    	view.setVal(field.value);
		    	view.on({
				    selected: function(records){
				    	if(records.length == 0) {
				    		Ext.MessageBox.alert('ThinkGsp','未检索到任何客户信息!');
				    	} else {
					    	custIdField.value = records[0].get('customerId');
					    	field.setValue('[' + records[0].get('customerCode') + ']' + records[0].get('customerName'));
				    	}
				    },
				    scope: this
				});
		    	view.show();	
	    }
	},
	//清楚客户Id
	clearCustId:function(field,e) {
		var custIdField = field.up('panel').down('hiddenfield[name=custId]');
		if(field.value == '') {
			//var custIdField = field.up('panel').down('hiddenfield[name=custId]');
			custIdField.setValue(null);
		}
	},
	//创建单据
	createBill:function(button) {
		var store = Ext.create('Ext.data.Store',{
			model: 'TS.model.rp.ArpBillModel',
			proxy:{
				url:'rp/arecbill/createARecBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			callback:function(records, operation, success) {
				var record = records[0];
				var billForm = Ext.create('TS.view.rp.RpARecBillEditor');
				billForm.setTitle('应收单-新增');
				billForm.down('form').loadRecord(record);
				billForm.initAssociation(record);
				savebtn = billForm.down('button[action=save]');
				savebtn.on({
					click:this.saveBill,
					scope: this
				});
				billForm.show();
			},
			scope:this
		});
	},
	
	saveBill:function(button) {
		var me = this;
		var form = button.up('window').down('form');
		var billModel = button.up('window').down('form').getRecord();
		var pass = form.isValid();
		if(pass) {
			if(billModel.get('custSuppId') == null || billModel.get('custSuppId') == 0) {
				pass = false;
			} 
			if(!pass) {
				form.down('textfield[name=customerCode]').markInvalid('客户id无效!');
			} else {
				form.down('textfield[name=customerCode]').markInvalid(null);
			}
		}
		if(!pass) {
			Ext.MessageBox.show({
				title:'单据验证',
				msg:'单据验证不通过！',
				buttons:Ext.Msg.OK,
				icon:Ext.Msg.WARNING
			});
			return false;
		} else {
			form.getForm().updateRecord(billModel);
			Ext.Ajax.request({
				url:'rp/arecbill/save.do',
				method:'POST',
				jsonData:billModel.data,
				success:function(response) {
			    	var data=Ext.decode(response.responseText);
			    	if(data.success==true){
			    		Ext.MessageBox.show({
			    			title:'单据保存',
			    			msg:data.msg,
			    			buttons:Ext.Msg.OK,
			    			icon:Ext.Msg.INFO
			    		});
			    		form.up('window').close();
			    		me.search(null);
			    	} else {
			    		Ext.MessageBox.show({
			    			title:'单据保存',
			    			msg:data.msg,
			    			buttons:Ext.Msg.OK,
			    			icon:Ext.Msg.ERROR
			    		});			    		
			    	}
				}
			});
		}	
	},
	//编辑单据
	editBill:function(button) {
		var grid = button.up('grid');
		if(!grid.getSelectionModel().hasSelection()) {
			Ext.Msg.show({
				title: '编辑应收单',
				msg: '您没有选择任何单据!',
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
			return;
		}
		var record = grid.getSelectionModel().getLastSelected();
		this.openBill(record);
	},
	dbclickBill:function(grid,record) {
		this.openBill(record);
	},
	openBill:function(record) {
		var store = Ext.create('Ext.data.Store',{
			model: 'TS.model.rp.ArpBillModel',
			proxy:{
				url:'rp/arecbill/getARecBill.do',
				type:'ajax',
				reader:{
					type:'json',
					root:''
				}
			},
			autoLoad:false
		});
		store.load({
			params : {billId:record.get('arpBillId')},
			callback:function(records, operation, success) {
				if(!success) {
					Ext.Msg.show({
						title: '编辑应收单',
						msg: '获取应收单出错',
						buttons: Ext.Msg.OK,
						icon: Ext.Msg.ERROR
					});
					return;
				}
				var record = records[0];
				if(record.get('archived') == true) {
					Ext.Msg.show({
						title: '编辑应收单',
						msg: '本单据已经归档，不允许编辑！',
						buttons: Ext.Msg.OK,
						icon: Ext.Msg.ERROR
					});
					return;
				}
				var billForm = Ext.create('TS.view.rp.RpARecBillEditor');
				billForm.setTitle('应收单-编辑');
				billForm.down('form').loadRecord(record);
				billForm.initAssociation(record);
				savebtn = billForm.down('button[action=save]');
				savebtn.on({
					click:this.saveBill,
					scope: this
				});
				billForm.show();
			},
			scope:this
		});
	},
	//删除单据
	deleteBill:function(button) {
		var me = this;
		var grid = button.up('grid');
		if(!grid.getSelectionModel().hasSelection()) {
			Ext.Msg.show({
				title: '删除应收单',
				msg: '您没有选择任何单据!',
				buttons: Ext.Msg.OK,
				icon: Ext.Msg.ERROR
			});
			return;
		}
		var record = grid.getSelectionModel().getLastSelected();
		if(record.get('archived')) {
			Ext.Msg.show({
				title:'删除应收单',
				msg:'您选择的单据已经归档，不允许删除!',
				buttons:Ext.Msg.OK,
				icon: Ext.Msg.WARNING
			});
			return;
		}
		Ext.Msg.show({
			title:'询问',
			msg: '您确定要删除应收单吗?',
			buttons:Ext.Msg.OKCANCEL,
			icon:Ext.Msg.QUESTION,
			fn:function(button) {
				if(button == 'ok') {
					me.doDeleteBill(grid,record);
				}
			}
		});
	},
	
	doDeleteBill:function(grid,record) {
		var billId = record.get('arpBillId');
		Ext.Ajax.request({
			url:'rp/arecbill/delete.do',
			params:{billId:billId},
			success:function(response) {
		    	var data=Ext.decode(response.responseText);
		    	if(data.success==true){
		    		Ext.MessageBox.show({
		    			title:'ThinkGsp',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.INFO
		    		});
		    		grid.store.remove(record);
		    	} else {
		    		Ext.MessageBox.show({
		    			title:'ThinkGsp',
		    			msg:data.msg,
		    			buttons:Ext.Msg.OK,
		    			icon:Ext.Msg.ERROR
		    		});			    		
		    	}
			}
		});
	},
	
	//归档单据
	archiveBill:function(button) {
		var grid = button.up('panel').up('panel').down('gridpanel');
		var records = grid.getSelectionModel().getSelection();
		if(records.length == 0) {
			Ext.MessageBox.alert('ThinkGsp','请选择要归档的单据！');
		} else {
			var cnt = records.length;
			Ext.each(records,function(record){
				if(record.get('archived')) {
					Ext.MessageBox.alert('ThinkGsp','单据:[' + record.get('arpBillCode') + ']已经归档。');
				} else {
					Ext.Ajax.request({
						url:'rp/arecbill/archive.do',
						params:{billId:record.get('arpBillId')},
						success:function(response,opts){
							var result = Ext.decode(response.responseText);
							if(result.success) {
								record.set('archived',true);	
								grid.reconfigure(grid.store);
								cnt--;
							} else {
								Ext.MessageBox.alert('错误信息','单据:[' + record.get('arpBillCode') + ']归档失败，原因:' + result.msg);
							}
						}
					});
				}
				if(cnt == 0) {
					Ext.MessageBox.alert('ThinkGsp',cnt + '份单据归档完成。');
				}
			});
		}
	},
	//反归档单据
	unArchiveBill:function(button) {
		var grid = button.up('panel').up('panel').down('gridpanel');
		var records = grid.getSelectionModel().getSelection();
		if(records.length == 0) {
			Ext.MessageBox.alert('ThinkGsp','请选择要反归档的单据！');
		} else {
			var cnt = records.length;
			Ext.each(records,function(record){
				if(!record.get('archived')) {
					Ext.MessageBox.alert('ThinkGsp','单据:[' + record.get('arpBillCode') + ']未归档，不允许反归档。');
				} else {
					Ext.Ajax.request({
						url:'rp/arecbill/unArchive.do',
						params:{billId:record.get('arpBillId')},
						success:function(response,opts){
							var result = Ext.decode(response.responseText);
							if(result.success) {
								record.set('archived',false);	
								cnt--;
								grid.reconfigure(grid.store);
							} else {
								Ext.MessageBox.show({
									title:'错误信息',
									msg:'单据:[' + record.get('arpBillCode') + ']反归档失败，原因:' + result.msg,
									buttons: Ext.Msg.OK,
									icon: Ext.window.MessageBox.INFO
								});
							}
						}
					});
				}
				if(cnt == 0) {
					Ext.MessageBox.alert('ThinkGsp',cnt + '份单据反归档完成。');
				}
			});
		}
	},
	//打印单据
	printBill:function(button) {
		var grid = button.up('panel').up('panel').down('gridpanel');
		Ext.ux.grid.Printer.print(grid);
	},
	//导出单据
	exportBill:function(button) {
//		var gridPanel= button.up('gridpanel');
//		var formater = 'excel'; //Ext.ux.exporter.Exporter.getFormatterByName('excel');
//		var dataURL='data:application/vnd.ms-excel; base64,'+
//							Ext.ux.exporter.Exporter.exportGrid(gridPanel,formater,{
//						        swfPath: 'extjs4/ux/exporter/downloadify.swf',
//						        downloadImage: 'extjs4/ux/exporter/download.png',
//						        width: 62,
//						        height: 22,
//						        downloadName: "download"
//						    });
//		window.location.href=dataURL;	
		
		var url="rp/arecbill/getArecbillXLS.do?";
		var begDate = button.up('panel').up('panel').down('datefield[name=begDate]').getRawValue();
		url += "begDate=" + begDate;
		var endDate = button.up('panel').up('panel').down('datefield[name=endDate]').getRawValue();
		url += "&endDate=" + endDate;
		var custId = button.up('panel').up('panel').down('hiddenfield[name=custId]').getValue();
		if(custId=="")
			url += "&custId=0";
		else
			url += "&custId=" + custId;
		window.open(url);
	}
	
});